package cn.tedu.csmall.product.service.impl;

import cn.tedu.csmall.commons.ex.ServiceException;
import cn.tedu.csmall.commons.util.PageInfoToPageDataConverter;
import cn.tedu.csmall.commons.vo.PageData;
import cn.tedu.csmall.commons.web.ServiceCode;
import cn.tedu.csmall.product.mapper.AlbumMapper;
import cn.tedu.csmall.product.mapper.PictureMapper;
import cn.tedu.csmall.product.mapper.SkuMapper;
import cn.tedu.csmall.product.mapper.SpuMapper;
import cn.tedu.csmall.product.pojo.entity.Album;
import cn.tedu.csmall.product.pojo.entity.Picture;
import cn.tedu.csmall.product.pojo.entity.Sku;
import cn.tedu.csmall.product.pojo.entity.Spu;
import cn.tedu.csmall.product.pojo.param.AlbumAddNewParam;
import cn.tedu.csmall.product.pojo.param.AlbumUpdateInfoParam;
import cn.tedu.csmall.product.pojo.vo.AlbumListItemVO;
import cn.tedu.csmall.product.pojo.vo.AlbumStandardVO;
import cn.tedu.csmall.product.service.IAlbumService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;


@Service
@Slf4j
//日志文件slf4j
public class AlbumServiceImpl implements IAlbumService {


    //不加Service不能自动装配
    @Autowired
    private AlbumMapper albumMapper;

    @Autowired
    private PictureMapper pictureMapper;

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private SkuMapper skuMapper;


    @Override
    public void addNew(AlbumAddNewParam albumAddNewParam) {

        log.debug("开始处理[添加相册]的业务，参数:{}", albumAddNewParam);

        //检查相册名称是否被占用，如果被占用，则抛出异常
        //select count(*) from pms_album where name = ?

        QueryWrapper<Album> queryWrapper = new QueryWrapper<>();

        //                      字段值
        queryWrapper.eq("name", albumAddNewParam.getName());
        int countByName = albumMapper.selectCount(queryWrapper);
        log.debug("根据相册名称统计匹配的相册数量，结果:{}", countByName);
        //如果相册存在大于0
        if (countByName > 0) {
            String message = "添加相册失败，相册名称已经被占用";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        Album album = new Album();

        //将数据复制                目标→→→→→→→→→→→→→→目地
        BeanUtils.copyProperties(albumAddNewParam, album);
        album.setGmtCreate(LocalDateTime.now());
        album.setGmtModified(LocalDateTime.now());
        log.debug("准备将新的相册数据写入到数据库,数据：{}", album);
        int rows = albumMapper.insert(album);
        if (rows != 1) {
            String message = "添加相册失败！服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }

        log.debug("将新的相册数据写入到数据库，完成！");


    }

    @Override
    public void delete(Long id) {
        log.debug("开始处理【删除相册】的业务，参数：{}", id);

        //检查相册是否存在，如果不存在，则抛出异常
        QueryWrapper<Album> queryWrapper = new QueryWrapper<>();
        //                      字段值
        queryWrapper.eq("id", id);
        int countById = albumMapper.selectCount(queryWrapper);
        log.debug("根据相册名称统计匹配的相册数量，结果:{}", countById);
        //如果相册存在大于0
        if (countById == 0) {
            String message = "删除相册失败，相册数据不存在";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        //检查是否有图片关联到了此相册，如果存在，则抛出异常
        QueryWrapper<Picture> queryWrapper2 = new QueryWrapper<>();
        //                      字段值
        queryWrapper.eq("album_id", id);
        int countByAlbumId = pictureMapper.selectCount(queryWrapper2);
        log.debug("根据相册ID统计匹配的图片数量，结果:{}", countByAlbumId);
        //如果相册存在大于0
        if (countByAlbumId > 0) {
            String message = "删除相册失败，仍有图片关联到此相册";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        //检查是否有SPU关联到了此相册，如果存在，则抛出异常

        QueryWrapper<Spu> queryWrapper3 = new QueryWrapper<>();
        //                      字段值
        queryWrapper.eq("album_id", id);
        int countByAlbumId2 = spuMapper.selectCount(queryWrapper3);
        log.debug("根据相册ID统计匹配的图片数量，结果:{}", countByAlbumId2);
        //如果相册存在大于0
        if (countByAlbumId2 > 0) {
            String message = "删除相册失败，仍有图片关联到此相册";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        //检查是否有SKU关联到了此相册，如果存在，则抛出异常

        QueryWrapper<Sku> queryWrapper4 = new QueryWrapper<>();
        //                      字段值
        queryWrapper.eq("album_id", id);
        int countByAlbumId3 = skuMapper.selectCount(queryWrapper4);
        log.debug("根据相册ID统计匹配的图片数量，结果:{}", countByAlbumId3);
        //如果相册存在大于0
        if (countByAlbumId3 > 0) {
            String message = "删除相册失败，仍有图片关联到此相册";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }


        albumMapper.deleteById(id);


    }

    @Override
    public void updateInfoById(Long id, AlbumUpdateInfoParam albumUpdateInfoParam) {
        log.debug("开始处理【修改相册详情】的业务，ID:{},参数：{}", id, albumUpdateInfoParam);
        QueryWrapper<Album> queryWrapper = new QueryWrapper<>();
        //                      字段值
        queryWrapper.eq("id", id);
        int countById = albumMapper.selectCount(queryWrapper);
        log.debug("根据相册名称统计匹配的相册数量，结果:{}", countById);
        //如果相册存在大于0
        if (countById == 0) {
            String message = "修改相册失败，相册数据不存在";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }


        //检查相册名称是否被其它相册占用，如果被占用，则抛出异常
        QueryWrapper<Album> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("name", albumUpdateInfoParam.getName())//xx=xx
                .ne("id", id) //xx!=xx
        ;
        int countByName = albumMapper.selectCount(queryWrapper2);
        log.debug("根据相册名称统计匹配的相册数量，结果:{}", countByName);
        //如果相册存在大于0
        if (countByName > 0) {
            String message = "添加相册失败，相册名称已经被占用";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }


        //执行修改
        Album album = new Album();
        BeanUtils.copyProperties(albumUpdateInfoParam, album);
        album.setId(id);
        int rows = albumMapper.updateById(album);
        if (rows != 1) {
            String message = "修改相册失败！服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
        log.debug("将新的相册数据更新入到数据库，完成！");
    }


    @Override
    public PageData<AlbumListItemVO> list(Integer pageNum) {
        Integer pageSize = 5;
        return list(pageNum, pageSize);
    }

    @Override
    public PageData<AlbumListItemVO> list(Integer pageNum, Integer pageSize) {
        log.debug("开始处理[查询相册列表]的业务，页码：{}，每页记录数:{}", pageNum, pageSize);
        PageHelper.startPage(pageNum, pageSize);
        List<AlbumListItemVO> list = albumMapper.list();
        PageInfo<AlbumListItemVO> pageInfo = new PageInfo<>(list);
        PageData<AlbumListItemVO> pageData = PageInfoToPageDataConverter.convert(pageInfo);
        log.debug("查询完成,即将返回：{}", pageData);
        return pageData;

    }


    @Override
    public AlbumStandardVO getStandardById(Long id) {
        log.debug("开始处理[根据ID查询相册详情]的业务，参数:{}", id);
        AlbumStandardVO queryResult = albumMapper.getStandardById(id);
        if (queryResult == null) {
            String message = "查询相册详情失败,相册数据不存在";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        return queryResult;

    }
}
